package com.leyou.user.web;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
/**
 * @author BaiZY on 2020/9/2.
 * @version 1.0
 */
@RestController
@RequestMapping("/info")
public class UserController {

    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 判断信息是否存在
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> exits(@PathVariable("data") String data, @PathVariable("type") Integer type){
        return ResponseEntity.ok(userService.exists(data,type));
    }

    /**
     * 根据用户名和密码查询
     * @param username
     * @param password
     * @return
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByPhoneAndPassword(@RequestParam("username")String username,@RequestParam("password") String password){
        return ResponseEntity.ok(userService.queryUserByPhoneAndPassword(username,password));
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone")String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 注册用户
     * @param code
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> register(
            @Valid User user,
            @RequestParam("code") String code
            ){
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("/me")
    public ResponseEntity<UserDetail> me(){
        return ResponseEntity.ok(UserContext.getUser());
    }
}
